/**
 * 创建API授权客户端请求对象
 */
package ms.core.gateway.request;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import lombok.Data;
import ms.core.common.AppException;
import ms.core.common.consts.SysErr;
import ms.core.gateway.system.Application;
import ms.core.tool.EncryptTool;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.SysTool;

@Data
public class CreateClientRequest {
	// 前端传参
	private String corpName;
	private String email;
	private List<String> funcs;
	private Date limitTime;
	// 后端补充数据
	private String clientId;
	private String clientSecret;
	private Date createTime;
	private int state=1;
	
	public static CreateClientRequest getInstance(Map<String, Object> body) {
		CreateClientRequest cli = JsonTool.objectToBean(body, CreateClientRequest.class);
		if (cli==null) throw new AppException(SysErr.SYS_PARAM_ERR);

		if (StrTool.isBlank(cli.getCorpName()))
			throw new AppException(SysErr.SYS_PARAM_ERR, "请输入企业名称.");
		if (StrTool.isBlank(cli.getEmail()))
			throw new AppException(SysErr.SYS_PARAM_ERR, "请输入联系邮箱.");
		if (cli.getFuncs()==null || cli.getFuncs().size()==0)
			throw new AppException(SysErr.SYS_PARAM_ERR, "未授予任何功能接口.");
		if (cli.getState()<0 || cli.getState()>2)
			throw new AppException(SysErr.SYS_PARAM_ERR, "API授权状态参数值错误.");

		String uid = SysTool.makeUUID("");
		String clientId = StringUtils.upperCase(Application.APP_NAME) + "_" + EncryptTool.randomUpperOrLowerCaseString(EncryptTool.sha256(uid));
		String clientSecret = EncryptTool.randomUpperOrLowerCaseString(EncryptTool.sha512(uid));
		cli.setClientId(clientId);
		cli.setClientSecret(clientSecret);
		cli.setCreateTime(new Date());
		return cli;
	}
}